package com.springBoot.springBootSysCore.filter;

import com.springBoot.springBootSysCore.common.config.Global;
import com.springBoot.springBootSysCore.common.utils.StringUtils;
import com.springBoot.springBootSysCore.listener.IndexListener;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Map;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class SessionFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private String official = Global.getConfig("official");
    private final static String[] notOfficialUrl = StringUtils.split(Global.getConfig("notOfficialUrl"), ",");

    /**
     * Servlet容器在销毁过滤器实例前调用该方法，这个方法中可以释放Servlet过滤器占用的资源
     */
    public void destroy() {
        //NDC.remove();
    }

    /**
     * 这个方法完成实际的过滤操作，当客户请求访问于过滤器关联的URL时，Servlet容器将先调用过滤器的doFilter方法。FilterChain参数用于访问后续过滤器
     */
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc) throws IOException, ServletException {
        HttpServletResponse response = (HttpServletResponse) res;

        HttpServletRequest httpReq = (HttpServletRequest) req;
        String ctxPath = httpReq.getContextPath();
        String requestUri = httpReq.getRequestURI(); // 请求的全路径,比如:
        String uri = requestUri.substring(ctxPath.length());// 全路径除去ctxPath
        String tarUri = uri.trim();
        if (tarUri.equals("/") || tarUri.equals("/a")) {
            fc.doFilter(req, res);
            return;
        }

        if ("false".equals(official)) {
            if (!StringUtils.endsWithAny(uri, notOfficialUrl) && !StringUtils.startsWithAny(uri, notOfficialUrl)/* && !StringUtils.containsAny(uri,notOfficialUrl)*/) {
                logger.info("=============session拦截==================");
                logger.info("=============请求ip:" + StringUtils.getRemoteAddr(httpReq) + "=============");
                logger.info("=============请求路径" + tarUri + "=============");
                Map<String, String[]> a = httpReq.getParameterMap();
                logger.info("=============请求参数:" + getParamString(a) + "=============");
                Cookie[] cookies = httpReq.getCookies();
                if (cookies != null) {
                    for (int i = 0; i < cookies.length; i++) {
                        logger.info("=============cookies：" + cookies[i].getName() + "-" + cookies[i].getValue() + "=============");
                    }
                } else {
                    logger.info("=============无cookies=============");
                }
                if (httpReq.getHeaderNames().hasMoreElements()) {
                    logger.info("=============请求头：" + httpReq.getHeaderNames().nextElement() + ":" + httpReq.getParameter(httpReq.getHeaderNames().nextElement()) + "=============");
                }

                response.setHeader("Content-Type", "application/json;charset=UTF-8");
                response.setHeader("Accept", "application/json");
            }
        }
        response.setHeader("Access-Control-Allow-Origin", "*");//解决跨域问题
        response.setHeader("Access-Control-Allow-Credentials", "true");


        if (!StringUtils.endsWithAny(uri, notOfficialUrl) && !StringUtils.startsWithAny(uri, notOfficialUrl)) {
            CustomHttpServletResponse cresponse = new CustomHttpServletResponse((HttpServletResponse) response);
            //		chain.doFilter(request,cresponse);
            //      cresponse.flushBuffer();
            //		fc.doFilter(req, res);
            fc.doFilter(req, cresponse);
            byte[] data = cresponse.getCopy();
            String htmStr = new String(data, response.getCharacterEncoding());
            logger.info("=============请求响应:" + htmStr + "=============");
            logger.info("=============session拦截结束==================");
        } else {
            fc.doFilter(req, res);
        }

        return;
    }

    /**
     * 这是Servlet过滤器的初始化方法，Servlet容器创建Servlet过滤器实例后将调用这个方法。在这个方法中可以读取web.xml文件中Servlet过滤器的初始化参数
     */
    public void init(FilterConfig config) throws ServletException {
    }

    private String getParamString(Map<String, String[]> map) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String[]> e : map.entrySet()) {
            sb.append(e.getKey()).append("=");
            String[] value = e.getValue();
            if (value != null && value.length == 1) {
                sb.append(value[0]).append("\t");
            } else {
                sb.append(Arrays.toString(value)).append("\t");
            }
        }
        return sb.toString();
    }
}
